/*
 * Created on Mar 23, 2005 TODO To change the template for this generated file
 * go to Window - Preferences - Java - Code Style - Code Templates
 */
package com.novix.portal.framework.dao.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.NotesException;
import lotus.domino.NotesFactory;
import lotus.domino.Session;
import lotus.domino.View;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.FastArrayList;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.novix.portal.framework.exceptions.ApplicationException;
import com.novix.portal.framework.model.impl.WebContact;
import com.novix.portal.framework.model.impl.WebOrganization;
import com.novix.portal.framework.util.IConstants;
import com.novix.utility.web.AttachmentLoader;
import com.novix.utility.web.Messages;

/**
 * @author edE TODO To change the template for this generated type comment go to Window - Preferences - Java - Code
 *         Style - Code Templates
 */
public class BaseDAO {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(BaseDAO.class);

    private static final boolean IS_DEBUG = logger.isDebugEnabled();

    /**
     * @param serverName
     * @param ienaddressesPath
     * @param session
     * @return
     * @throws NotesException
     */

    private List bindWebContactBeanPicsOrNo(String captiveName, String serverName, String ienaddressesPath,
            Session session) throws NotesException {
        List list;
        Database notesDatabase = session.getDatabase(serverName, ienaddressesPath);
        if (!notesDatabase.isOpen())
            notesDatabase.open();
        View view = notesDatabase.getView("weballcontacts");
        Document doc = view.getFirstDocument();

        list = new ArrayList();
        while (doc != null) {
//            if (IS_DEBUG)
//                logger.debug(doc.getUniversalID());
            WebContact webContact = new WebContact();
            webContact.setCompanyName(doc.getItemValueString("CompanyName"));
            Vector vec = doc.getItemValue("captives");
            if (logger.isDebugEnabled())
                for (Iterator iter = vec.iterator(); iter.hasNext();) {
                    String element = (String) iter.next();
                    logger.debug("captives are :" + element);
                }
            List captiveList = new FastArrayList(vec);

            webContact.setCaptives(captiveList);
            webContact.setFullName(doc.getItemValueString("fullname"));
            webContact.setInternetAddress(doc.getItemValueString("InternetAddress"));
            webContact.setJobTitle(doc.getItemValueString("JobTitle"));
            webContact.setSpouseName(doc.getItemValueString("Spouse"));
            webContact.setOfficePhoneNumber(doc.getItemValueString("OfficePhoneNumber"));
            webContact.setCompanyId(doc.getItemValueString("IENCompanyDocumentUniqueID"));
            webContact.setOfficeFaxNumber(doc.getItemValueString("OfficeFAXPhoneNumber"));
            setWebSiteLinkForContacts(doc, webContact);
            webContact.setId(doc.getUniversalID());
            ArrayList catList = getCategories(doc);
            webContact.setCategories(catList);
            webContact.setLastName(doc.getItemValueString("LastName"));
            setAttachmentName(session, serverName, doc, webContact);
            list.add(webContact);
            Document nextDoc = view.getNextDocument(doc);
            doc.recycle();
            doc = nextDoc;

        }
        return list;
    }

    public List selectAllWebContacts(String serverConnectionString, String token, String captiveName,
            String serverName, String ienaddressesPath) {
        Session session = null;
        List list = null;
        try {
            if (token != null) {
                session = NotesFactory.createSession(serverConnectionString, Messages.getString("CacheLoader.name"),
                        Messages.getString("CacheLoader.password"));
            }
            Database notesDatabase = session.getDatabase(serverName, ienaddressesPath);
            if (!notesDatabase.isOpen())
                notesDatabase.open();

            View view = notesDatabase.getView("webcontactphoto");

            Document doc = view.getFirstDocument();

            list = new ArrayList();
            while (doc != null) {
                if (IS_DEBUG)
                    logger.debug(doc.getUniversalID());
                if ((doc.getItemValueString("Captives") != null && doc.getItemValueString("Captives").trim()
                        .compareToIgnoreCase(captiveName.trim()) == 0)) {
                    WebContact webContact = new WebContact();
                    webContact.setCompanyName(doc.getItemValueString("CompanyName"));
                    webContact.setCaptives(doc.getItemValue("captives"));
                    webContact.setFullName(doc.getItemValueString("fullname"));
                    webContact.setSpouseName(doc.getItemValueString("Spouse"));
                    webContact.setInternetAddress(doc.getItemValueString("InternetAddress"));
                    webContact.setJobTitle(doc.getItemValueString("JobTitle"));
                    webContact.setOfficePhoneNumber(doc.getItemValueString("OfficePhoneNumber"));
                    webContact.setCompanyId(doc.getItemValueString("IENCompanyDocumentUniqueID"));
                    setWebSiteLinkForContacts(doc, webContact);
                    webContact.setId(doc.getUniversalID());
                    ArrayList catList = getCategories(doc);
                    webContact.setCategories(catList);
                    webContact.setLastName(doc.getItemValueString("LastName"));
                    setAttachmentName(session, serverName, doc, webContact);
                    list.add(webContact);
                }
                Document nextDoc = view.getNextDocument(doc);
                doc.recycle();
                doc = nextDoc;

            }

        } catch (NotesException e) {
            String errorMessage = "Error in selectAllWebOrganizations ..." + " " + e.id + " " + e.text;
            logger.error(errorMessage, e);
            throw new ApplicationException(errorMessage);
        } finally {
            try {
                session.recycle();
            } catch (NotesException e) {
                String errorMessage = "Error in recycling notessession ...";
                logger.error(errorMessage + " " + e.id + " " + e.text, e);
            }
        }

        return list;

    }

    public List selectAllWebOrganizations(String serverConnectionString, String token, String captiveName,
            String serverName, String ienaddressesPath) {
        Session session = null;
        List list = null;
        try {
            if (token != null) {
                session = NotesFactory.createSession(serverConnectionString, Messages.getString("CacheLoader.name"),
                        Messages.getString("CacheLoader.password"));
            }
            Database notesDatabase = session.getDatabase(serverName, ienaddressesPath);
            if (!notesDatabase.isOpen())
                notesDatabase.open();

            View view = notesDatabase.getView("WebMemberCo");

            Document doc = view.getFirstDocument();

            Document temp = null; // sets the temp for garbage collection
            // immediately

            list = new ArrayList();
            while (doc != null) {
                bindWebOrgResultSet(captiveName, list, doc);
                temp = view.getNextDocument(doc); // get the next one
                doc.recycle(); // recycle the one we're done with
                doc = temp;

            }

        } catch (NotesException e) {
            String errorMessage = "Error in selectAllWebOrganizations ..." + " " + e.id + " " + e.text;
            logger.error(errorMessage, e);
            throw new ApplicationException(errorMessage);
        } finally {
            try {
                session.recycle();
            } catch (NotesException e) {
                String errorMessage = "Error in recycling notessession ...";
                logger.error(errorMessage + " " + e.id + " " + e.text, e);
            }
        }
        BeanComparator comp = new BeanComparator("companyName");
        Collections.sort(list, comp);
        return list;

    }

    /**
     * @param doc
     * @param webOrg
     * @throws NotesException
     */
    public void setRegionLinks(Document doc, WebOrganization webOrg) throws NotesException {
        if (doc.getItemValueString("WebSite") != null && StringUtils.isNotEmpty(doc.getItemValueString("WebSite"))) {
            webOrg.setLink(doc.getItemValueString("WebSite"));
        }
        webOrg.setIenregion(doc.getItemValueString("IENREGION"));
    }

    /**
     * @param doc
     * @param webContact
     * @throws NotesException
     */
    public void setWebSiteLinkForContacts(Document doc, WebContact webContact) throws NotesException {
        if (!StringUtils.isEmpty(doc.getItemValueString("WebSite")))
            webContact.setWebSite(doc.getItemValueString("WebSite"));
        else
            webContact.setWebSite("");
    }

    /**
     * @param session
     * @param serverName
     * @param doc
     * @param webContact
     * @throws NotesException
     */
    protected void setAttachmentName(Session session, String serverName, Document doc, WebContact webContact)
            throws NotesException {
        webContact.setImageLink(IConstants.NO_IMAGE_FOUND);
        Vector vec = session.evaluate("@AttachmentNames", doc);
        for (Iterator iter = vec.iterator(); iter.hasNext();) {
            String element = (String) iter.next();
            if (logger.isInfoEnabled() && webContact.getLastName().compareToIgnoreCase("kulmer") == 0)
                logger.info(webContact.getFullName() + " -- file name is: " + element);
            if (element != null && AttachmentLoader.isValidFileName(element) && element.trim().length() > 0) {
                String link = "http://" + serverName + "/" + session.evaluate("@WebDbName", doc).elementAt(0) + "/0/"
                        + doc.getUniversalID() + "/$FILE/" + element.trim() + "?open";
                webContact.setImageLink(link);

            }
        }
    }

    /**
     * @param doc
     * @return
     * @throws NotesException
     */
    protected ArrayList getCategories(Document doc) throws NotesException {
        Vector vec = doc.getItemValue("Categories");
        ArrayList catList = new ArrayList();
        for (Iterator iter = vec.iterator(); iter.hasNext();) {
            String element = (String) iter.next();
            catList.add(element.trim());
        }
        return catList;
    }

    public List selectAllWebOrganizationsByQuery(String query, String serverConnectionString, String token,
            String captiveName, String serverName, String ienaddressesPath) {
        Session session = null;
        List list = null;
        try {
            if (token != null) {
                session = NotesFactory.createSession(serverConnectionString, Messages.getString("CacheLoader.name"),
                        Messages.getString("CacheLoader.password"));
            }
            Database notesDatabase = session.getDatabase(serverName, ienaddressesPath);
            if (!notesDatabase.isOpen())
                notesDatabase.open();
            if (IS_DEBUG)
                logger.debug("query is ..." + query);
            View view = notesDatabase.getView("WebMemberCo");
            int docCounter = view.FTSearch(query);

            list = new ArrayList();
            int counter = 1;
            while (counter <= docCounter) {
                Document doc = view.getNthDocument(counter); // get the next one
                bindWebOrgResultSet(captiveName, list, doc);
                doc.recycle(); // recycle the one we're done with

                counter++;
            }

        } catch (NotesException e) {
            String errorMessage = "query : " + query + " : Error in selectAllWebOrganizations ..." + " " + e.id + " "
                    + e.text;
            logger.error(errorMessage, e);
            throw new ApplicationException(errorMessage, e);
        } finally {
            try {
                session.recycle();
            } catch (NotesException e) {
                String errorMessage = "Error in recycling notessession ...";
                logger.error(errorMessage + " " + e.id + " " + e.text, e);
            }
        }
        BeanComparator comp = new BeanComparator("companyName");
        Collections.sort(list, comp);
        return list;

    }

    /**
     * @param session
     * @param serverName
     * @param iePath
     * @return
     */
    public List selectAllWebContactsPicsOrNo(Session session, String serverName, String iePath) {
        List list = null;
        try {

            list = bindWebContactBeanPicsOrNo(null, serverName, iePath, session);

        } catch (NotesException e) {
            String errorMessage = "Error in selectAllWebOrganizations ...";
            logger.error(errorMessage + " " + e.id + " " + e.text, e);
            throw new ApplicationException(errorMessage);
        } finally {
            try {
                session.recycle();
            } catch (NotesException e) {
                String errorMessage = "Error in recycling notessession ...";
                logger.error(errorMessage + " " + e.id + " " + e.text, e);
            }
        }

        return list;
    }

    public List selectAllWebContactsPicsOrNo(String serverConnectionString, String token, String captiveName,
            String serverName, String ienaddressesPath, boolean showAllPicsOrNo) {

        Session session = null;
        List list = null;
        try {
            if (token != null) {
                session = NotesFactory.createSession(serverConnectionString, Messages.getString("CacheLoader.name"),
                        Messages.getString("CacheLoader.password"));
            }
            list = bindWebContactBeanPicsOrNo(captiveName, serverName, ienaddressesPath, session);

        } catch (NotesException e) {
            String errorMessage = "Error in selectAllWebOrganizations ...";
            logger.error(errorMessage + " " + e.id + " " + e.text, e);
            throw new ApplicationException(errorMessage);
        } finally {
            try {
                session.recycle();
            } catch (NotesException e) {
                String errorMessage = "Error in recycling notessession ...";
                logger.error(errorMessage + " " + e.id + " " + e.text, e);
            }
        }

        return list;
    }

    /**
     * @param captiveName
     * @param list
     * @param doc
     * @throws NotesException
     */
    private void bindWebOrgResultSet(String captiveName, List list, Document doc) throws NotesException {
        if ((doc.getItemValueString("captives") != null && doc.getItemValueString("captives").compareToIgnoreCase(
                captiveName) == 0)
                && (doc.getItemValueString("IENMemberName") != null && doc.getItemValueString("IENMemberName")
                        .compareToIgnoreCase(doc.getItemValueString("CompanyName")) == 0)) {
            WebOrganization webOrg = new WebOrganization();
            webOrg.setCompanyName(doc.getItemValueString("CompanyName"));
            setRegionLinks(doc, webOrg);
            webOrg.setOfficeCity(doc.getItemValueString("OfficeCity"));
            webOrg.setOfficePhoneNumber(doc.getItemValueString("OfficePhoneNumber"));
            webOrg.setOfficeState(doc.getItemValueString("OfficeState"));
            webOrg.setOrgComment(doc.getItemValueString("OrgComment"));            
            webOrg.setCompanyId(doc.getItemValueString("IENCompanyDocumentUniqueID"));
            webOrg.setCompanyDocumentUniqueID(doc.getItemValueString("IENCompanyDocumentUniqueID"));
            webOrg.setCaptives(doc.getItemValue("captives"));
            webOrg.setNAICS(getNaics(doc));
            list.add(webOrg);
        }
    }

    protected ArrayList getNaics(Document doc) throws NotesException {        
        Vector vec = doc.getItemValue("NAICS");
        if(vec==null || vec.size()<1)
            return null;
        ArrayList catList = new FastArrayList(vec.size());
        for (Iterator iter = vec.iterator(); iter.hasNext();) {
            String element = (String) iter.next();
            if(element.indexOf('-')!=-1){
                element = StringUtils.left(element, element.indexOf('-'));
                if(org.apache.commons.lang.math.NumberUtils.isNumber(element)){
                       if(!StringUtils.isEmpty(element)){
                        catList.add(element.trim());
                        if(IS_DEBUG)
                            logger.debug("substring of naics: " + element);                
                    }
                }
            }
        }
        return catList;
    }
}
